
from threading import Thread
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import detectMss
import sys
import threading
import numpy as np
import pynput

global mousePressed
mousePressed = 0

class TransWin(QWidget):
    '''实现全透明窗口'''

    def __init__(self, width, height, Kp, Ki, ally):
        super(TransWin, self).__init__()

        # 去除背景
        self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

        # 窗口设置
        self.setWindowTitle('Test')
        self.setObjectName('MyWidget')
        self.setStyleSheet("QWidget#MyWidget{background:grey;}")
        self.x = detectMss.sizeList[0]
        self.y = detectMss.sizeList[1]
        self.width = width
        self.height = height
        self.move(self.x, self.y)
        self.setGeometry(self.y, self.x, width, height)
        self.ally = ally
        self.pen1 = QPen()                      
        self.pen1.setColor(Qt.red)
        self.pen1.setWidth(3)
        self.pen2 = QPen()                      
        self.pen2.setColor(Qt.green)
        self.pen2.setWidth(2)
        self.pen3 = QPen()
        self.pen3.setColor(Qt.blue)
        self.pen3.setWidth(2)        
        self.timer = QBasicTimer()
        self.bboxes = []
        self.bboxesLast = []
        self.xDis = 0
        self.yDis = 0
        self.targetIndex = 0
        self.refCnt = 0
        self.ctr = pynput.mouse.Controller()
        self.Kp = Kp
        self.Ki = Ki
        self.sumErrx = 0
        self.sumErry = 0     
        self.steadyShoot = 0
        if self.timer.isActive() == 0:
            self.timer.start(50, self)

    def timerEvent(self,e):
        temp = detectMss.detFifo.qsize()
        if detectMss.detFifo.qsize() > 0:
            self.bboxes = detectMss.detFifo.get()
            self.refCnt = 0
        else:
            if self.refCnt < 1:
                self.refCnt += 1
            else: #50ms未检测到，清box
                self.bboxes = []
                self.sumErrx = 0
                self.sumErry = 0
        if len(self.bboxes) > 0:
            centerDis = 65535
            self.xDis = 0
            self.yDis = 0
            i = 0
            for bbox in self.bboxes:
                label = bbox['label']
                #判断敌友
                if label != self.ally:
                    box = [bbox['x0'], bbox['y0'], bbox['x1'], bbox['y1']]
                    head = self.headPos(box) #计算头的坐标
                    temp = np.power((head[0] - self.width / 2), 2) + np.power((head[1] - self.height / 2), 2)
                    #寻找最近的头
                    if temp < centerDis:
                        centerDis = temp
                        self.xDis = self.width / 2 - head[0]
                        self.yDis = self.height / 2 - head[1]
                        #更新目标索引
                        self.targetIndex = i
                i += 1
            #centerDis = np.power(centerDis, 0.5)
            self.moveMousePid()
        #压枪
        global mousePressed
        if mousePressed:
            self.steadyShoot = 3
        else:
            self.steadyShoot = 0
        self.update()

    def moveMousePid(self):
        self.sumErrx += self.xDis
        self.sumErry += self.yDis
        dx = self.xDis * self.Kp + self.sumErrx * self.Ki
        dy = self.yDis * self.Ki + self.sumErry * self.Ki + self.steadyShoot
        self.ctr.move(dx, dy)
    def headPos(self, box):
        return [int((box[0] + box[2])/2), int(box[1] - (box[3] - box[1]) / 7)]

    def paintEvent(self, QPaintEvent):
        painter = QPainter(self)                
        painter.setPen(self.pen1)
        painter.drawRect(10, 10, self.width - 20, self.height - 20)
        if len(self.bboxes) > 0:
            painter.setPen(self.pen2)
            i = 0
            for bbox in self.bboxes:
                label = bbox['label']
                box = [bbox['x0'], bbox['y0'], bbox['x1'], bbox['y1']]
                if i == self.targetIndex:
                    painter.setPen(self.pen1)
                elif label == self.ally:
                    painter.setPen(self.pen2)
                else:
                    painter.setPen(self.pen3)
                painter.drawRect(box[0], box[1], box[2] - box[0], box[3] - box[1])
                painter.drawText(box[0], box[1] - 10, label)
                i += 1
        
  
Kp = -0.4
Ki = -0.01
class QtWindow(threading.Thread):
    def __init__(self, threadID, name, ally):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.ally = ally
    def run(self):
        app = QApplication(sys.argv)
        window = TransWin(detectMss.sizeList[2], detectMss.sizeList[3], Kp, Ki, self.ally)
        window.show()
        sys.exit(app.exec_())

def on_click(x, y, button, pressed):
    global mousePressed
    if button == pynput.mouse.Button.left:
        if pressed:
            mousePressed = 1
        else:
            mousePressed = 0 




if __name__ == '__main__':
    
    threadDetect = detectMss.threading_detect(1, 'mssDetect')
    threadWin = QtWindow(2, 'Window', 'police')
    listener = pynput.mouse.Listener(on_click=on_click)
    listener.start()
    threadWin.start()
    threadDetect.start()
    threadWin.join()
    threadDetect.join()
    listener.join()